package com.cloudweb.oa.controller;

import cn.js.fan.db.ListResult;
import cn.js.fan.util.ErrMsgException;
import cn.js.fan.util.ParamUtil;
import cn.js.fan.util.ResKeyException;
import cn.js.fan.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloudweb.oa.api.IDesktopCard;
import com.cloudweb.oa.cache.UserCache;
import com.cloudweb.oa.entity.User;
import com.cloudweb.oa.exception.ValidateException;
import com.cloudweb.oa.module.desktop.DesktopCard;
import com.cloudweb.oa.module.desktop.DesktopCardFactory;
import com.cloudweb.oa.module.desktop.DesktopCardUtil;
import com.cloudweb.oa.security.AuthUtil;
import com.cloudweb.oa.service.IDocService;
import com.cloudweb.oa.service.PortalService;
import com.cloudweb.oa.utils.ConstUtil;
import com.cloudweb.oa.utils.SpringUtil;
import com.cloudweb.oa.vo.Result;
import com.cloudwebsoft.framework.db.JdbcTemplate;
import com.cloudwebsoft.framework.util.LogUtil;
import com.redmoon.oa.Config;
import com.redmoon.oa.flow.FormDb;
import com.redmoon.oa.person.UserDb;
import com.redmoon.oa.person.UserDesktopSetupDb;
import com.redmoon.oa.pvg.Privilege;
import com.redmoon.oa.ui.LocalUtil;
import com.redmoon.oa.ui.PortalDb;
import com.redmoon.oa.visual.Attachment;
import com.redmoon.oa.visual.FormDAO;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

@Api(tags = "门户管理")
@Controller
@RequestMapping("/portal")
public class PortalController {
    @Autowired
    HttpServletRequest request;

    @Autowired
    PortalService portalService;

    @Autowired
    AuthUtil authUtil;

    @Autowired
    UserCache userCache;

    @Autowired
    IDocService docService;

    @ApiOperation(value = "取得相应类型的图型配置", notes = "取得相应类型的图型配置", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "chartType", value = "图型的类型", required = true, dataType = "String"),
    })
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/getChartTypes", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<JSONArray> getChartTypes(String chartType) {
        return new Result<>(portalService.getChartTypes(chartType));
    }

    @ApiOperation(value = "门户列表", notes = "门户列表", httpMethod = "POST")
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> list() {
        JSONArray arr = new JSONArray();
        PortalDb portalDb = new PortalDb();
        String sql = "select id from " + portalDb.getTable().getName() + " where user_name=? order by kind asc, orders asc";
        for (Object o : portalDb.list(sql, new Object[]{ConstUtil.USER_SYSTEM})) {
            portalDb = (PortalDb) o;

            JSONObject json = new JSONObject();
            json.put("isFixed", portalDb.getInt("is_fixed"));
            json.put("orders", portalDb.getInt("orders"));
            json.put("id", portalDb.getLong("id"));
            json.put("name", portalDb.getString("name"));
            json.put("depts", portalDb.getString("depts"));
            json.put("roles", portalDb.getString("roles"));
            json.put("icon", portalDb.getString("icon"));
            json.put("status", portalDb.getInt("status") == 1);
            json.put("kind", portalDb.getInt("kind"));
            json.put("device", portalDb.getInt("device"));
            arr.add(json);
        }
        return new Result<>(arr);
    }

    @ApiOperation(value = "用户可见的PC端门户列表", notes = "用户可见的PC端门户列表，不包含首页", httpMethod = "POST")
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/listPortal", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> listPortal() {
        JSONArray arr = new JSONArray();
        PortalDb pd = new PortalDb();
        Vector<PortalDb> v = pd.listByPc();
        for (PortalDb portalDb : v) {
            if (portalDb.getInt("status") == 1 && portalDb.canUserSee(authUtil.getUserName())) {
                JSONObject json = new JSONObject();
                json.put("isFixed", portalDb.getInt("is_fixed"));
                json.put("orders", portalDb.getInt("orders"));
                json.put("id", portalDb.getLong("id"));
                json.put("name", portalDb.getString("name"));
                json.put("depts", portalDb.getString("depts"));
                json.put("roles", portalDb.getString("roles"));
                json.put("icon", portalDb.getString("icon"));
                json.put("status", portalDb.getInt("status") == 1);
                arr.add(json);
            }
        }
        return new Result<>(arr);
    }

    @ApiOperation(value = "用户可见的移动端门户列表", notes = "用户可见的移动端门户列表，含首页", httpMethod = "POST")
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/listPortalByMobile", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> listPortalByMobile() {
        JSONArray arr = new JSONArray();
        PortalDb pd = new PortalDb();
        Vector<PortalDb> v = pd.listByMobile();
        for (PortalDb portalDb : v) {
            if (portalDb.getInt("status") == 1 && portalDb.canUserSee(authUtil.getUserName())) {
                JSONObject json = new JSONObject();
                json.put("isFixed", portalDb.getInt("is_fixed"));
                json.put("orders", portalDb.getInt("orders"));
                json.put("id", portalDb.getLong("id"));
                json.put("name", portalDb.getString("name"));
                json.put("icon", portalDb.getString("icon"));

                // 取出轮播图片ID
                String setup = portalDb.getString("setup");
                com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(setup);
                com.alibaba.fastjson.JSONArray layoutList = jsonObject.getJSONArray("layoutList");
                for (Object o : layoutList) {
                    com.alibaba.fastjson.JSONObject layout = (com.alibaba.fastjson.JSONObject) o;
                    com.alibaba.fastjson.JSONObject item = layout.getJSONObject("item");
                    if (item.getString("type").equals("CarouselPicture")) {
                        com.alibaba.fastjson.JSONObject meta = item.getJSONObject("meta");
                        if (meta.containsKey("carouselPictureId")) {
                            int carouselPictureId = meta.getIntValue("carouselPictureId");
                            json.put("carouselPictureId", carouselPictureId);
                            break;
                        }
                    }
                }

                arr.add(json);
            }
        }
        return new Result<>(arr);
    }

    @ApiOperation(value = "手机端全部门户列表", notes = "手机端全部门户列表，用于后台管理", httpMethod = "POST")
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/listAllPortalByMoile", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> listAllPortalByMoile() {
        JSONArray arr = new JSONArray();
        JSONObject json = new JSONObject();
        json.put("value", 0);
        json.put("name", "公共");
        arr.add(json);

        PortalDb pd = new PortalDb();
        Vector<PortalDb> v = pd.listAllByMobile();
        for (PortalDb portalDb : v) {
            if (portalDb.getInt("status") == 1) {
                json = new JSONObject();
                json.put("value", portalDb.getLong("id"));
                json.put("name", portalDb.getString("name"));
                arr.add(json);
            }
        }

        return new Result<>(arr);
    }

    @ApiOperation(value = "用于菜单上的门户列表", notes = "用于菜单的门户列表", httpMethod = "POST")
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/listPortalForMenu", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> listPortalForMenu() {
        JSONArray arr = new JSONArray();
        PortalDb pd = new PortalDb();
        Vector<PortalDb> v = pd.listByKind(PortalDb.KIND_MENU);
        for (PortalDb portalDb : v) {
            boolean canSee = portalDb.canUserSee(authUtil.getUserName());
            if (canSee) {
                JSONObject json = new JSONObject();
                json.put("isFixed", portalDb.getInt("is_fixed"));
                json.put("orders", portalDb.getInt("orders"));
                json.put("id", portalDb.getLong("id"));
                json.put("name", portalDb.getString("name"));
                json.put("depts", portalDb.getString("depts"));
                json.put("roles", portalDb.getString("roles"));
                json.put("icon", portalDb.getString("icon"));
                json.put("status", portalDb.getInt("status") == 1);
                arr.add(json);
            }
        }

        return new Result<>(arr);
    }

    @ApiOperation(value = "取得门户的名称", notes = "取得门户的名称", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "portals", value = "门名ID，以逗号分隔", required = true, dataType = "String"),
    })
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/listPortalNames", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> listPortalNames(@RequestParam String portals) {
        JSONArray arr = new JSONArray();
        PortalDb portalDb = new PortalDb();
        String[] ary = portals.split(",");
        for (String strId : ary) {
            long id = StrUtil.toLong(strId, -1);
            portalDb = (PortalDb) portalDb.getQObjectDb(id);
            JSONObject json = new JSONObject();
            json.put("id", portalDb.getLong("id"));
            json.put("name", portalDb.getString("name"));
            arr.add(json);
        }
        return new Result<>(arr);
    }

    @ApiOperation(value = "添加", notes = "添加", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "门户名称", required = true, dataType = "String"),
            @ApiImplicitParam(name = "icon", value = "门户图标", required = true, dataType = "String"),
            @ApiImplicitParam(name = "depts", value = "可见部门", required = false, dataType = "String"),
            @ApiImplicitParam(name = "roles", value = "可见角色", required = true, dataType = "String"),
            @ApiImplicitParam(name = "status", value = "状态", required = true, dataType = "Boolean"),
            @ApiImplicitParam(name = "kind", value = "类型", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "device", value = "类型", required = true, dataType = "Integer"),
    })
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> create(@RequestParam String name, @RequestParam String icon, String depts, String roles,
                                 @RequestParam(defaultValue="true") Boolean status, @RequestParam(defaultValue="0")Integer kind,
                                 @RequestParam(defaultValue = "0") Integer device) {
        PortalDb portalDb = new PortalDb();
        boolean re;
        try {
            int isFixed = 1;
            String setup = "";
            re = portalDb.create(new JdbcTemplate(), new Object[]{ConstUtil.USER_SYSTEM, name, portalDb.getNextOrders(ConstUtil.USER_SYSTEM), PortalDb.SYSTEM_ID_NONE, icon, isFixed, depts, roles, status ? 1 : 0, kind, setup, device});
        } catch (ResKeyException e) {
            LogUtil.getLog(getClass()).error(e);
            return new Result<>(false, e.getMessage(request));
        }
        return new Result<>(re);
    }

    @ApiOperation(value = "修改", notes = "修改", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "门户ID", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "name", value = "门户名称", required = true, dataType = "String"),
            @ApiImplicitParam(name = "icon", value = "门户图标", required = true, dataType = "String"),
            @ApiImplicitParam(name = "depts", value = "可见部门", required = false, dataType = "String"),
            @ApiImplicitParam(name = "roles", value = "可见角色", required = false, dataType = "String"),
            @ApiImplicitParam(name = "orders", value = "排序号", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "status", value = "状态", required = true, dataType = "Boolean"),
            @ApiImplicitParam(name = "kind", value = "类型", required = true, dataType = "Integer"),
    })
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> update(@RequestParam Long id, @RequestParam String name, @RequestParam(required = true) String icon, String depts,
                                 String roles, @RequestParam Integer orders, @RequestParam(defaultValue="true") Boolean status,
                                 @RequestParam(defaultValue="0")Integer kind,
                                 @RequestParam(defaultValue = "0") Integer device) {
        PortalDb portalDb = new PortalDb();
        portalDb = (PortalDb) portalDb.getQObjectDb(id);
        int isFixed = 1;
        boolean re;
        String setup = portalDb.getString("setup");
        try {
            re = portalDb.save(new JdbcTemplate(), new Object[]{name, orders, icon, isFixed, depts, roles, setup, status ? 1 : 0, kind, device, id});
        } catch (SQLException e) {
            LogUtil.getLog(getClass()).error(e);
            return new Result<>(false, e.getMessage());
        }
        return new Result<>(re);
    }

    @ApiOperation(value = "复制门户", notes = "复制门户", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "门户ID", required = true, dataType = "Long"),
    })
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/copy", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> copy(@RequestParam Long id) {
        PortalDb portalDb = new PortalDb();
        portalDb = (PortalDb) portalDb.getQObjectDb(id);
        String name = portalDb.getString("name") + " 复制";
        String icon = portalDb.getString("icon");
        String depts = portalDb.getString("depts");
        String roles = portalDb.getString("roles");
        int status = portalDb.getInt("status");
        int kind = portalDb.getInt("kind");
        String setup = portalDb.getString("setup");
        int device = portalDb.getInt("device");

        int isFixed = 1;
        boolean re;
        try {
            re = portalDb.create(new JdbcTemplate(), new Object[]{ConstUtil.USER_SYSTEM, name, portalDb.getNextOrders(ConstUtil.USER_SYSTEM), PortalDb.SYSTEM_ID_NONE, icon, isFixed, depts, roles, status, kind, setup, device});
        } catch (ResKeyException e) {
            LogUtil.getLog(getClass()).error(e);
            return new Result<>(false, e.getMessage(request));
        }
        return new Result<>(re);
    }

    @ApiOperation(value = "取得门户设计", notes = "取得门户设计", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "门户ID", required = true, dataType = "Long"),
    })
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/getSetup", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> getSetup(@RequestParam Long id) {
        PortalDb portalDb = new PortalDb();
        portalDb = (PortalDb) portalDb.getQObjectDb(id);
        if (portalDb == null) {
            return new Result<>(false, "门户不存在");
        }
        JSONObject json = new JSONObject();
        json.put("id", portalDb.getInt("id"));
        json.put("setup", portalDb.getString("setup"));
        return new Result<>(json);
    }

    @ApiOperation(value = "修改门户设计", notes = "修改门户设计", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "门户ID", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "setup", value = "门户设计内容", required = true, dataType = "Long"),
    })
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/updateSetup", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> updateSetup(@RequestParam Long id, @RequestParam String setup) {
        PortalDb portalDb = new PortalDb();
        portalDb = (PortalDb) portalDb.getQObjectDb(id);
        portalDb.set("setup", setup);
        try {
            return new Result<>(portalDb.save());
        } catch (ResKeyException e) {
            LogUtil.getLog(getClass()).error(e);
            return new Result<>(false, e.getMessage(request));
        }
    }

    @ApiOperation(value = "排序", notes = "排序", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "门户ID", required = true, dataType = "String"),
    })
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/sort", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> sort(@RequestParam String ids) {
        boolean re = false;
        String[] arr = StrUtil.split(ids, ",");
        PortalDb portalDb = new PortalDb();
        try {
            for (int i = 0; i < arr.length; i++) {
                portalDb = (PortalDb) portalDb.getQObjectDb(StrUtil.toLong(arr[i]));
                portalDb.set("orders", i + 1);
                re = portalDb.save();
            }
        } catch (ResKeyException e) {
            LogUtil.getLog(getClass()).error(e);
            return new Result<>(false, e.getMessage());
        }
        return new Result<>(re);
    }

    @ApiOperation(value = "删除门户", notes = "删除门户", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "门户ID", required = true, dataType = "Long"),
    })
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/del", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> del(@RequestParam(required = true) Long id) {
        boolean re;
        try {
            PortalDb portalDb = new PortalDb();
            portalDb = (PortalDb)portalDb.getQObjectDb(id);
            re = portalDb.del();
        } catch (ResKeyException e) {
            LogUtil.getLog(getClass()).error(e);
            return new Result<>(false, e.getMessage());
        }
        return new Result<>(re);
    }

    @ApiOperation(value = "取得某个卡片", notes = "取得某个卡片", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "卡片ID", required = true, dataType = "Long"),
    })
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/getCard", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})
    public Result<Object> getCard(@RequestParam Long id) {
        String userName = authUtil.getUserName();
        boolean isAdmin = authUtil.isUserPrivValid(request, ConstUtil.PRIV_ADMIN);
        DesktopCardUtil desktopCardUtil = new DesktopCardUtil();
        DesktopCard desktopCard = desktopCardUtil.getCardById(id);
        IDesktopCard iDesktopCard = DesktopCardFactory.getIDesktopCard(desktopCard);
        if (iDesktopCard == null) {
            LogUtil.getLog(getClass()).warn(desktopCard.getTitle() + " " + desktopCard.getCardType() + " 不存在");
            return new Result<>(false, desktopCard.getTitle() + " " + desktopCard.getCardType() + " 不存在");
        }

        JSONObject json = new JSONObject();
        boolean canSeeCard = false;
        String roles = desktopCard.getRoles();
        if (isAdmin) {
            canSeeCard = true;
        }
        else {
            if (!StringUtils.isEmpty(roles)) {
                String[] arr = StrUtil.split(roles, ",");
                for (String roleCode : arr) {
                    if (userCache.isUserOfRole(userName, roleCode)) {
                        canSeeCard = true;
                        break;
                    }
                }
            }
            else {
                canSeeCard = true;
            }
        }
        if (!canSeeCard) {
            return new Result<>(false, desktopCard.getTitle() + " 无权查看");
        }

        json.put("icon", iDesktopCard.getIcon());
        json.put("title", iDesktopCard.getTitle());
        json.put("isLink", iDesktopCard.isLink());
        json.put("url", iDesktopCard.getUrl());
        json.put("startVal", iDesktopCard.getStartVal());
        json.put("endVal", iDesktopCard.getEndVal(request));
        json.put("unit", iDesktopCard.getUnit());
        json.put("type", desktopCard.getCardType());
        json.put("moduleCode", desktopCard.getModuleCode());
        json.put("bgMode", desktopCard.getBgMode());
        json.put("bgColor", desktopCard.getBgColor());
        json.put("bgColorCustom", desktopCard.getBgColorCustom());
        json.put("bgImage", desktopCard.getBgImage());
        json.put("query", iDesktopCard.getQuery());
        json.put("style", desktopCard.getStyle());
        json.put("img", desktopCard.getImg());
        return new Result<>(json);
    }

    @ApiOperation(value = "取得门户中的卡片列表", notes = "取得门户中的卡片列表", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "门户ID", required = true, dataType = "Long"),
    })
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/listCard", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})
    public Result<Object> listCard(@RequestParam Long id) {
        JSONArray ary = new JSONArray();
        String userName = authUtil.getUserName();
        boolean isAdmin = authUtil.isUserPrivValid(request, ConstUtil.PRIV_ADMIN);
        DesktopCardUtil desktopCardUtil = new DesktopCardUtil();
        List<DesktopCard> cardList = desktopCardUtil.listByPortal(id);
        for (DesktopCard desktopCard : cardList) {
            IDesktopCard iDesktopCard = DesktopCardFactory.getIDesktopCard(desktopCard);
            if (iDesktopCard == null) {
                LogUtil.getLog(getClass()).warn(desktopCard.getTitle() + " " + desktopCard.getCardType() + " 不存在");
                continue;
            }

            JSONObject json = new JSONObject();

            boolean canSeeCard = false;
            String roles = desktopCard.getRoles();
            if (isAdmin) {
                canSeeCard = true;
            }
            else {
                if (!StringUtils.isEmpty(roles)) {
                    String[] arr = StrUtil.split(roles, ",");
                    for (String roleCode : arr) {
                        if (userCache.isUserOfRole(userName, roleCode)) {
                            canSeeCard = true;
                            break;
                        }
                    }
                }
                else {
                    canSeeCard = true;
                }
            }
            if (!canSeeCard) {
                continue;
            }

            ary.add(json);
            json.put("icon", iDesktopCard.getIcon());
            json.put("title", iDesktopCard.getTitle());
            json.put("isLink", iDesktopCard.isLink());
            if (iDesktopCard.isLink()) {
                json.put("url", desktopCard.getUrl());
            } else {
                json.put("url", iDesktopCard.getUrl());
            }
            json.put("startVal", iDesktopCard.getStartVal());
            json.put("endVal", iDesktopCard.getEndVal(request));
            json.put("unit", iDesktopCard.getUnit());
            json.put("type", desktopCard.getCardType());
            json.put("moduleCode", desktopCard.getModuleCode());
            json.put("bgMode", desktopCard.getBgMode());
            json.put("bgColor", desktopCard.getBgColor());
            json.put("bgColorCustom", desktopCard.getBgColorCustom());
            json.put("bgImage", desktopCard.getBgImage());
            json.put("query", iDesktopCard.getQuery());

            json.put("style", desktopCard.getStyle());
            json.put("color", desktopCard.getColor());
            json.put("img", desktopCard.getImg());
        }
        return new Result<>(ary);
    }

    @ApiOperation(value = "取得所有的卡片", notes = "取得所有的卡片", httpMethod = "POST")
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/listAllCard", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})
    public Result<Object> listAllCard() {
        JSONArray ary = new JSONArray();
        String userName = authUtil.getUserName();
        boolean isAdmin = authUtil.isUserPrivValid(request, ConstUtil.PRIV_ADMIN);
        DesktopCardUtil desktopCardUtil = new DesktopCardUtil();
        List<DesktopCard> cardList = desktopCardUtil.listAll();
        for (DesktopCard desktopCard : cardList) {
            IDesktopCard iDesktopCard = DesktopCardFactory.getIDesktopCard(desktopCard);
            if (iDesktopCard == null) {
                LogUtil.getLog(getClass()).warn(desktopCard.getTitle() + " " + desktopCard.getCardType() + " 不存在");
                continue;
            }

            boolean canSeeCard = false;
            String roles = desktopCard.getRoles();
            if (isAdmin) {
                canSeeCard = true;
            }
            else {
                if (!StringUtils.isEmpty(roles)) {
                    String[] arr = StrUtil.split(roles, ",");
                    for (String roleCode : arr) {
                        if (userCache.isUserOfRole(userName, roleCode)) {
                            canSeeCard = true;
                            break;
                        }
                    }
                }
                else {
                    canSeeCard = true;
                }
            }
            if (!canSeeCard) {
                continue;
            }

            JSONObject json = new JSONObject();
            json.put("id", iDesktopCard.getId());
            json.put("name", iDesktopCard.getName());
            ary.add(json);
        }
        return new Result<>(ary);
    }

    @ApiOperation(value = "取得门户中的应用卡片", notes = "取得门户中的应用卡片", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "门户ID", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "count", value = "数量", required = true, dataType = "Integer"),
    })
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/listCardByApplication", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})
    public Result<Object> listCardByApplication(@RequestParam Long id, @RequestParam Integer count) {
        JSONArray ary = new JSONArray();
        Config cfg = Config.getInstance();
        int flowOpStyle = StrUtil.toInt(cfg.get("flowOpStyle"), 1);
        String userName = authUtil.getUserName();
        boolean isAdmin = authUtil.isUserPrivValid(request, ConstUtil.PRIV_ADMIN);
        DesktopCardUtil desktopCardUtil = new DesktopCardUtil();
        List<DesktopCard> cardList = desktopCardUtil.listByApplication(id, count);
        for (DesktopCard desktopCard : cardList) {
            IDesktopCard iDesktopCard = DesktopCardFactory.getIDesktopCard(desktopCard);
            if (iDesktopCard == null) {
                LogUtil.getLog(getClass()).warn(desktopCard.getTitle() + " " + desktopCard.getCardType() + " 不存在");
                continue;
            }

            JSONObject json = new JSONObject();
            boolean canSeeCard = false;
            String roles = desktopCard.getRoles();
            if (isAdmin) {
                canSeeCard = true;
            }
            else {
                if (!StringUtils.isEmpty(roles)) {
                    String[] arr = StrUtil.split(roles, ",");
                    for (String roleCode : arr) {
                        if (userCache.isUserOfRole(userName, roleCode)) {
                            canSeeCard = true;
                            break;
                        }
                    }
                }
                else {
                    canSeeCard = true;
                }
            }
            if (!canSeeCard) {
                continue;
            }

            ary.add(json);

            json.put("icon", iDesktopCard.getIcon());
            json.put("title", iDesktopCard.getTitle());
            json.put("isLink", iDesktopCard.isLink());
            json.put("url", iDesktopCard.getUrl());
            json.put("startVal", iDesktopCard.getStartVal());
            json.put("endVal", iDesktopCard.getEndVal(request));
            json.put("unit", iDesktopCard.getUnit());
            json.put("type", desktopCard.getCardType());
            json.put("moduleCode", desktopCard.getModuleCode());
            json.put("bgMode", desktopCard.getBgMode());
            json.put("bgColor", desktopCard.getBgColor());
            json.put("bgColorCustom", desktopCard.getBgColorCustom());
            json.put("bgImage", desktopCard.getBgImage());
            json.put("color", desktopCard.getColor());
            json.put("query", iDesktopCard.getQuery());
            json.put("flowOpStyle", flowOpStyle);
            json.put("flowType", desktopCard.getFlowType());
        }
        return new Result<>(ary);
    }

    @ApiOperation(value = "取得模块中的卡片", notes = "取得模块中的卡片", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "moduleCode", value = "模块编码", required = true, dataType = "String"),
    })
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/listCardByModule", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})
    public Result<Object> listCardByModule(@RequestParam String moduleCode) {
        JSONArray ary = new JSONArray();
        String userName = authUtil.getUserName();
        boolean isAdmin = authUtil.isUserPrivValid(request, ConstUtil.PRIV_ADMIN);
        DesktopCardUtil desktopCardUtil = new DesktopCardUtil();
        List<DesktopCard> cardList = desktopCardUtil.listByModule(moduleCode);
        for (DesktopCard desktopCard : cardList) {
            IDesktopCard iDesktopCard = DesktopCardFactory.getIDesktopCard(desktopCard);
            if (iDesktopCard == null) {
                LogUtil.getLog(getClass()).warn(desktopCard.getTitle() + " " + desktopCard.getCardType() + " 不存在");
                continue;
            }

            JSONObject json = new JSONObject();
            ary.add(json);

            boolean canSeeCard = false;
            String roles = desktopCard.getRoles();
            if (isAdmin) {
                canSeeCard = true;
            }
            else {
                if (!StringUtils.isEmpty(roles)) {
                    String[] arr = StrUtil.split(roles, ",");
                    for (String roleCode : arr) {
                        if (userCache.isUserOfRole(userName, roleCode)) {
                            canSeeCard = true;
                            break;
                        }
                    }
                }
                else {
                    canSeeCard = true;
                }
            }
            if (!canSeeCard) {
                continue;
            }

            json.put("icon", iDesktopCard.getIcon());
            json.put("title", iDesktopCard.getTitle());
            json.put("isLink", iDesktopCard.isLink());
            json.put("url", iDesktopCard.getUrl());
            json.put("startVal", iDesktopCard.getStartVal());
            json.put("endVal", iDesktopCard.getEndVal(request));
            json.put("unit", iDesktopCard.getUnit());
            json.put("type", desktopCard.getCardType());
            json.put("moduleCode", desktopCard.getModuleCode());
            json.put("bgMode", desktopCard.getBgMode());
            json.put("bgColor", desktopCard.getBgColor());
            json.put("bgColorCustom", desktopCard.getBgColorCustom());
            json.put("bgImage", desktopCard.getBgImage());
            json.put("query", iDesktopCard.getQuery());
            json.put("color", desktopCard.getColor());
        }
        return new Result<>(ary);
    }

    @ApiOperation(value = "图片轮播列表", notes = "图片轮播列表", httpMethod = "POST")
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/listCarouselPicture", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})
    public Result<Object> listCarouselPicture() {
        JSONArray ary = new JSONArray();
        String formCode = "carousel_picture";
        FormDAO fdao = new FormDAO();
        String sql = "select id from " + FormDb.getTableName(formCode);
        Vector<FormDAO> v = fdao.list(formCode, sql);
        for (FormDAO dao : v) {
            JSONObject json = new JSONObject();
            ary.add(json);

            json.put("id", dao.getId());
            json.put("name", dao.getFieldValue("name"));
        }
        return new Result<>(ary);
    }

    @ApiOperation(value = "取得图片轮播", notes = "取得图片轮播", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "rowCount", value = "数量", required = true, dataType = "Integer"),
    })
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/getCarouselPictureInfo", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})
    public Result<Object> getCarouselPictureInfo(@RequestParam Long id, @RequestParam Integer rowCount) {
        String formCode = "carousel_picture";
        FormDAO fdao = new FormDAO();
        String sql = "select id from " + FormDb.getTableName(formCode) + " where id=" + id;
        Vector<FormDAO> v = fdao.list(formCode, sql);
        if (v.isEmpty()) {
            return new Result<>(false, "图片轮播设置的记录不存在");
        }

        String dirCode = v.elementAt(0).getFieldValue("dir_code");
        return new Result<>(docService.listImage(dirCode, rowCount));
    }

}
